<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <z-paging
    ref="pagingRef"
    v-model="msgList"
    :paging-style="{'top': '0',background: '#F2F3F7'}"
    :empty-view-text="prodEmptyTips"
    :empty-view-img="emptyCoupon"
    :empty-view-img-style="{width:'460rpx',height:'460rpx'}"
    class="page-platform-message"
    @query="onLoadMsgList"
  >
    <view class="Mall4j platform-message notice-message my-message">
      <!-- #ifdef H5 -->
      <!-- <view class="top-title">
      <view class="my-message">我的消息</view>
    </view> -->
      <!-- #endif -->
      <template v-if="isAuthorities">
        <!-- 客服消息 -->
        <view class="service-message">
          <view
            v-for="(item, index) in msgList"
            :key="index"
            class="item unread"
            @tap="toChat(item)"
          >
            <view class="logo">
              <img-show
                :src="item.pic"
                :def-img-inx="2"
              />
            </view>
            <view class="text-box">
              <view class="name">
                {{ item.nickName }}
              </view>
              <view class="des">
                {{ getMessageText(item.lastMessage) }}
              </view>
            </view>
            <view class="time-box">
              <view class="time">
                {{ item.timestampString||'time' }}
              </view>
              <view
                v-if="item.unread"
                class="unread-box"
              >
                <view class="number">
                  {{ item.unread }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <empty-tips
        v-else
        :tips-list="['你没有访问权限']"
      />
    </view>
  </z-paging>
</template>

<script setup>
import emptyCoupon from '@/static/images/empty-tips.png'
import util from '@/utils/util'
import { Convert } from '@/utils/convert'
import { ConversationWrap } from '@/utils/ConversationWrap'
import { WKSDK, ConversationAction } from 'wukongimjssdk'
const isLoaded = ref(false) // 列表是否加载完毕
const msgList = ref([])
const prodEmptyTips = ref('您还没有消息记录')
let shopInfo = ''
const isAuthorities = ref(false)
const userStore = useUserStore()

const shopId = computed(() => {
  return userStore.shopId
})

/**
 * 生命周期函数--监听页面加载
 */
onLoad(() => {
  getShopInfo()
})

onShow(() => {
  isAuthorities.value = util.isAuthorities('message:message:view')
  if (shopInfo) {
    WKSDK.shared().conversationManager.addConversationListener(conversationListener) // 监听最近会话列表的变化
    pagingRef.value?.reload()
  }
})
WKSDK.shared().config.provider.syncConversationsCallback = async () => {
  const data = await http.request({
    url: '/shop/wuKongIm/conversation/sync/page',
    method: 'get',
    data: params
  }).then(({ data }) => {
    const resultConversations = []
    const conversationList = data.records
    if (conversationList) {
      conversationList.forEach((v) => {
        const conversation = Convert.toConversation(v)
        conversation.lastMessage.content.text = JSON.parse(conversation.lastMessage?.content.text)
        resultConversations.push(conversation)
      })
    }
    return resultConversations
  })
  return data
}
onUnload(() => {
  WKSDK.shared().conversationManager.removeConversationListener(conversationListener) // 移除最近会话列表监听
  WKSDK.shared().disconnect()
})

/**
 * 根据tabType类型 获取消息数据
 */
const pagingRef = ref(null)
let params = {}
const onLoadMsgList = async (current, size) => {
  const url = '/shop/wuKongIm/conversation/sync/page'
  isLoaded.value = false
  const reqData = {
    current,
    size,
    version: 0
  }
  params = {
    url,
    method: 'GET',
    data: reqData
  }
  const remoteConversations = await WKSDK.shared().conversationManager.sync() // 同步最近会话列表
  if (remoteConversations && remoteConversations.length > 0) {
    const conversationWraps = sortConversations(remoteConversations.map(conversation => new ConversationWrap(conversation)))
    pagingRef.value.complete(conversationWraps)
  }
}
// 判断是否为JSON格式
const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}

/**
 * 获取店铺信息
 */
const getShopInfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET',
    data: {
      shopId: shopId.value
    }
  }
  http.request(params).then(({ data: res }) => {
    shopInfo = res
    if (shopInfo) {
      getWuKongIm()
      WKSDK.shared().conversationManager.addConversationListener(conversationListener) // 监听最近会话列表的变化
    }
  })
}

// 去客服聊天
const toChat = (item) => {
  uni.navigateTo({
    url: '/pages/chat/chat?userId=' + item.userId + '&userName=' + item.nickName + '&isDestroy=' + item.isDestroy
  })
}

const getWuKongIm = () => {
  const params = {
    url: '/shop/wuKongIm/registerOrLogin?token=' + uni.getStorageSync('bbcToken_us'),
    method: 'POST'
  }
  http.request(params).then(({ data }) => {
    const config = WKSDK.shared().config
    config.addr = import.meta.env.VITE_APP_WS_IM_API
    config.uid = data.uid // 用户uid（需要在悟空通讯端注册过）
    config.token = data.token// 用户token （需要在悟空通讯端注册过）
    config.debug = true
    config.deviceFlag = 1
    WKSDK.shared().config = config
    WKSDK.shared().connect()
  })
}

// 排序最近会话列表
const sortConversations = (conversations) => {
  let newConversations = conversations
  if (!newConversations) {
    newConversations = msgList.value
  }
  if (!newConversations || newConversations.length <= 0) {
    return []
  }
  const sortAfter = newConversations.sort((a, b) => {
    let aScore = a.timestamp
    let bScore = b.timestamp
    if (a.extra?.top === 1) {
      aScore += 1000000000000
    }
    if (b.extra?.top === 1) {
      bScore += 1000000000000
    }
    return bScore - aScore
  })
  return sortAfter
}
const conversationListener = async (conversation, action) => {
  if (action === ConversationAction.add) {
    msgList.value = [new ConversationWrap(conversation), ...(msgList.value || [])]
  } else if (action === ConversationAction.update) {
    const index = msgList.value?.findIndex(item => item.channel.channelID === conversation.channel.channelID && item.channel.channelType === conversation.channel.channelType)
    if (isJSON(conversation.lastMessage?.content.text)) {
      msgList.value[index] = new ConversationWrap(conversation)
      msgList.value = sortConversations()
    }
  }
}
const getMessageText = (message) => {
  if (isJSON(message.content.text)) {
    message.content.text = JSON.parse(message.content.text)
  }
  if (message.content.text?.msgType === 1 || message.content.text?.msgType === -1 || message.content.text?.type === -5) {
    return message.content?.text.msg
  } else if (message.content.text?.msgType === 4) {
    return '[商品链接]'
  } else if (!message.content.text?.msgType) {
    return message.content.text?.content || ''
  } else {
    return '[图片]'
  }
}

</script>

<style lang="scss" scoped>
@import "./message-box.scss";
</style>
